//
//  WONewWorkOrderViewController.m
//  WOPrototype
//
//  Created by Olof Millberg on 2010-04-22.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "WONewWorkOrderViewController.h"
#import "WONewAddressSection.h"
#import "WOPrioritySection.h"
#import "WOContactSection.h"
#import "WOTextSection.h"
#import "SQLiteReader.h"
#import "WOPerson.h"
#import "TextCell.h"

@implementation WONewWorkOrderViewController

#pragma mark Initialization Methods

/* Get an instance of the class */
- (id) init
{
	if (self = [super initWithStyle:UITableViewStyleGrouped])
		self.workOrder = [[WorkOrder alloc] init];
	return self;
}

/* Dellocate stuff */
- (void) dealloc
{
	[priorities release];
	[super dealloc];
}

/* The view is loaded for the first time */
- (void) viewDidLoad
{
	[super viewDidLoad];
	
	//Set navigation bar title.
	UILabel *titleView = [[[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 200.0f, 30.0f)] autorelease];
	[titleView setBackgroundColor:[UIColor clearColor]];
	[titleView setTextColor:[UIColor whiteColor]];
	[titleView setTextAlignment:UITextAlignmentCenter];
	[titleView setText:@"Ny arbetsorder"];
	self.navigationItem.titleView = titleView;
	
	//Fix back button.
	UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
								   initWithTitle:@"Tillbaka" 
								   style:UIBarButtonItemStyleBordered 
								   target:nil
								   action:@selector(backButton)];
	self.navigationItem.backBarButtonItem = backButton;
	[backButton release];
	
	self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Klar"
																			  style:UIBarButtonItemStyleDone 
																			 target:self 
																			 action:@selector(addWorkOrder:)];
	self.navigationItem.rightBarButtonItem.enabled = NO;
	
	self.tableView.sectionHeaderHeight = 2;
	self.tableView.sectionFooterHeight = 2;
	
	//Used for keyboard not hiding text fields.
	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector (keyboardDidShow:)
												 name: UIKeyboardDidShowNotification object:nil];
	
	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector (keyboardWillHide:)
												 name: UIKeyboardWillHideNotification object:nil];
	
	//Get priority types from database.
	SQLiteReader *sqlite = [[SQLiteReader alloc] initWithDatabase:@"trawoh.sql"];
	priorities = [[sqlite getPriorityTypes] retain];
	[sqlite release];
	
	// Add sections
	self.sections = [NSMutableArray array];
	[self.sections addObject:[WONewAddressSection newAddressSectionWithTitle:@"Adress"]];
	[self.sections addObject:[WOTextSection textSectionWithTitle:@"Felbeskrivning" text:workOrder.description]];
	[self.sections addObject:[WOPrioritySection prioritySectionWithTitle:@"Prioritet"]];
	[self.sections addObject:[WOContactSection contactSectionWithTitle:@"Kontaktpersoner" 
														   contactList:workOrder.contactPersons 
															  editable:YES]];
	[self.sections addObject:[WOContactSection contactSectionWithTitle:@"Arbetsledare" 
														   contactList:workOrder.workLeaders 
															  editable:YES]];
	[self.sections addObject:[WOContactSection contactSectionWithTitle:@"Tilldelade" 
														   contactList:workOrder.employees 
															  editable:YES]];
}

#pragma mark -

#pragma mark GUI Methods

/* Handle iPhone screen tilting */
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

- (void) keyboardDidShow: (NSNotification *)notif 
{
	// If keyboard is visible, return
	if (keyboardVisible) 
		return;
	
	// Get the size of the keyboard.
	NSDictionary* info = [notif userInfo];
	NSValue* aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];
	CGSize keyboardSize = [aValue CGRectValue].size;
	
	// Resize the scroll view to make room for the keyboard
	CGRect viewFrame = self.tableView.frame;
	viewFrame.size.height -= keyboardSize.height;
	
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:0.3f];
	self.tableView.frame = viewFrame;
	[UIView commitAnimations];
	
	// Keyboard is now visible
	keyboardVisible = YES;
}

- (void) keyboardWillHide: (NSNotification *)notif 
{
	//Is the keyboard visible?
	if (!keyboardVisible) 
		return;
		
	[NSTimer scheduledTimerWithTimeInterval:0.001f target:self 
								   selector:@selector(resetView:) 
								   userInfo:nil repeats:NO];
	//Keyboard is no longer visible.
	keyboardVisible = NO;	
}

- (void) resetView:(NSTimer*)timer
{
	[timer release];
	if (!keyboardVisible)
		self.tableView.frame = CGRectMake(0, 0, self.view.superview.frame.size.width, self.view.superview.frame.size.height);
}

#pragma mark -

#pragma mark Self Made Methods

/* Creates the work order */
- (void) addWorkOrder:(id)sender
{	
	//Set up database connection
	SQLiteReader *sqlite = [[SQLiteReader alloc] initWithDatabase:@"trawoh.sql"];	
	[sqlite createNewWorkOrder:self.workOrder];
	[sqlite release];
	
	//Pop the view and go back to the list of work orders.
	[self.navigationController popViewControllerAnimated:YES];
}

/* Makes sure all compulsory info is entered */
- (BOOL) readyToCreate
{
	return self.workOrder.address.street.length > 0
		&& self.workOrder.address.zipCode.length == 5
		&& self.workOrder.address.area.length > 0
		&& self.workOrder.address.city.length > 0
		&& self.workOrder.description.length > 0
		&& self.workOrder.contactPersons.count > 0
		&& self.workOrder.workLeaders.count > 0;
}

/* The priority is changed */
- (void) priorityChanged:(NSString *)priority
{
	workOrder.priority = priority;
}

/* Handles assignment of contact persons, work leaders and employees */
- (void) addContactCell:(AddContactCell *)addContactCell didSelectPerson:(WOPerson *)person
{
	NSMutableArray *contactList = ((WOContactSection *)[sections objectAtIndex:addContactCell.tag]).contactList;
	[contactList addObject:person];

	[self.tableView reloadData];
	
	//Ok to create new work order?
	self.navigationItem.rightBarButtonItem.enabled = [self readyToCreate];
}

/* Checks if a WOPerson exist in a NSMutableArray of WOPersons */
- (BOOL) doesPerson:(WOPerson *) aPerson existIn:(NSMutableArray *) somePersons
{
	BOOL exists = NO;
	for(WOPerson *currentPerson in somePersons)
	{
		if([currentPerson.socialID isEqualToString: aPerson.socialID])
		{
			exists = YES;
			break;
		}
	}
	
	return exists;
}

#pragma mark -

#pragma mark WONewAddressDelegate Methods

- (void) newAddressCell:(NewAddressCell *)addressCell streetChanged:(NSString *)newStreet
{
	workOrder.address.street = newStreet;
	
	//Ok to create new work order?
	self.navigationItem.rightBarButtonItem.enabled = [self readyToCreate];
}

- (void) newAddressCell:(NewAddressCell *)addressCell areaChanged:(NSString *)newArea
{
	workOrder.address.area = newArea;
	
	//Ok to create new work order?
	self.navigationItem.rightBarButtonItem.enabled = [self readyToCreate];
}

- (void) newAddressCell:(NewAddressCell *)addressCell postalCodeChanged:(NSString *)newPostalCode
{
	workOrder.address.zipCode = newPostalCode;
	
	//Ok to create new work order?
	self.navigationItem.rightBarButtonItem.enabled = [self readyToCreate];
}

- (void) newAddressCell:(NewAddressCell *)addressCell cityChanged:(NSString *)newCity
{
	workOrder.address.city = newCity;
	
	//Ok to create new work order?
	self.navigationItem.rightBarButtonItem.enabled = [self readyToCreate];
}

#pragma mark -

#pragma mark UINoteView Delegate Methods

- (BOOL) noteView:(WONewNoteViewController *)aNoteView shouldReturnWithText:(NSString *)text
{
	workOrder.description = text;
	
	for (WOTableSection *section in sections)
	{
		if ([section isKindOfClass:[WOTextSection class]])
		{
			((WOTextSection *)section).text = workOrder.description;
			break;
		}
	}
	
	[self.tableView reloadData];
	
	//Ok to create new work order?
	self.navigationItem.rightBarButtonItem.enabled = [self readyToCreate];
	
	return YES;
}

#pragma mark -

#pragma mark WOContactCellDelegate

- (void) contactCellDeleteButtonPressed:(ContactCell *)aContactCell
{
	NSMutableArray *contactList = ((WOContactSection *)[sections objectAtIndex:aContactCell.tag]).contactList;
	[contactList removeObject:aContactCell.contactPerson];
	
	[self.tableView reloadData];
	
	//Ok to create new work order?
	self.navigationItem.rightBarButtonItem.enabled = [self readyToCreate];
}

#pragma mark -

#pragma mark UITableView Methods

/* Sets the content of the UITableViewCells */
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	UITableViewCell *cell = [super tableView:aTableView cellForRowAtIndexPath:indexPath];
	
	// Enter the content.
	
	// Address
	if ([cell isKindOfClass:[NewAddressCell class]])
	{
		((NewAddressCell *) cell).delegate = self;
	}
	// Description
	else if ([cell isKindOfClass:[TextCell class]])
	{
		((TextCell *)cell).placeHolder = @"Skriv en felbeskrivning...";
		((TextCell *)cell).text = workOrder.description;
		((TextCell *)cell).title = @"Felbeskrivning";
		((TextCell *)cell).editable = YES;
		((TextCell *)cell).delegate = self;
		((TextCell *)cell).viewController = self;
	}
	// Priority
	else if ([cell isKindOfClass:[PriorityCell class]])
	{
		((PriorityCell *)cell).priority = workOrder.priority;
		((PriorityCell *)cell).priorities = priorities;
		((PriorityCell *)cell).delegate = self;
	}
	// Contacts
	else if ([cell isKindOfClass:[ContactCell class]])
	{
		NSMutableArray *contactList = ((WOContactSection*)[self.sections objectAtIndex:indexPath.section]).contactList;

		((ContactCell*)cell).contactPerson = [contactList objectAtIndex:indexPath.row];
		((ContactCell*)cell).tag = indexPath.section;
		((ContactCell*)cell).editable = YES;
		((ContactCell*)cell).delegate = self;
		((ContactCell*)cell).viewController = self;
	}
	else if ([cell isKindOfClass:[AddContactCell class]])
	{
		((AddContactCell *) cell).tag = indexPath.section;
		((AddContactCell *) cell).delegate = self;
		((AddContactCell *) cell).viewController = self;
	}
	
	return cell;
}

-(BOOL)tableView:(UITableView*)aTableView canEditRowAtIndexPath:(NSIndexPath*)indexPath
{
	return NO;
}

-(BOOL)tableView:(UITableView*)atableView canMoveRowAtIndexPath:(NSIndexPath*)indexPath
{
	return NO;
}

#pragma mark -

@end